<?php

namespace app\controller;

use think\Db;
use think\Request;

/**
 * User Controller
 * 处理用户相关操作
 */
class User extends Base
{
    /**
     * 用戶中心首頁
     */
    public function index()
    {
        // 檢查用戶登錄狀態
        if (empty($this->_user_id)) {
            $this->redirect('/login');
        }
        
        // 獲取用戶統計信息
        $stats = [
            'total_downloads' => $this->getUserActionCount('download'),
            'total_favorites' => $this->getUserActionCount('like'),
            'desktop_downloads' => $this->getUserActionCount('download', ['desktop', 'dynamic_desktop']),
            'mobile_downloads' => $this->getUserActionCount('download', ['mobile', 'dynamic_mobile']),
            'desktop_favorites' => $this->getUserActionCount('like', ['desktop', 'dynamic_desktop']),
            'mobile_favorites' => $this->getUserActionCount('like', ['mobile', 'dynamic_mobile'])
        ];
        
        // 獲取最近的下載記錄（前6個）
        $recentDownloads = $this->getUserActionsByType('download', [], 6);
        
        // 獲取最近的收藏記錄（前6個）
        $recentFavorites = $this->getUserActionsByType('like', [], 6);
        
        $this->assign([
            'stats' => $stats,
            'recentDownloads' => $recentDownloads,
            'recentFavorites' => $recentFavorites,
            'page_title' => '用戶中心',
            'page_description' => '管理您的桌布收藏和下載記錄。',
        ]);
        
        return $this->fetch();
    }
    
    /**
     * 獲取用戶操作數量統計
     */
    private function getUserActionCount($actionType, $wallpaperTypes = [], $limit = null)
    {
        $query = Db::name('user_actions')
            ->alias('ua')
            ->join('wallpaper wi', 'ua.image_id = wi.id')
            ->where([
                'ua.user_id' => $this->_user_id,
                'ua.action_type' => $actionType
            ]);
        
        if (!empty($wallpaperTypes)) {
            $query->where('wi.type', 'in', $wallpaperTypes);
        }
        
        return $query->count();
    }
    
    /**
     * 添加用户操作记录（喜欢/下载）
     * @param Request $request
     * @return \think\response\Json
     */
    public function addAction($image_id,$action_type)
    {
        try {
            // 获取请求参数
            $image_id = intval($image_id);
            $action_type = trim($action_type);
            // debug_dump($image_id,$action_type);
            
            // 参数验证
            if (empty($image_id)) {
                return $this->jsonResponse([], 400, '桌布ID不能为空');
            }
            
            if (!in_array($action_type, ['like', 'download'])) {
                return $this->jsonResponse([], 400, '操作类型无效');
            }
            
            // 获取用户ID
            $user_id = $this->_user_id;
            if (empty($user_id)) {
                return $this->jsonResponse([], 401, '请先登录');
            }
            
            // 检查桌布是否存在
            $image = Db::name('wallpaper')->where('id', $image_id)->find();
            if (!$image) {
                return $this->jsonResponse([], 404, '桌布不存在');
            }
            $action_field = $action_type == 'like' ? 'like_cnt' : 'download_cnt';
            Db::name('wallpaper')->where('id', $image_id)->setInc($action_field);
            
            // 检查是否已经存在该操作记录
            $existing = Db::name('user_actions')
                ->where([
                    'user_id' => $user_id,
                    'image_id' => $image_id,
                    'action_type' => $action_type
                ])
                ->find();
            
            if ($existing) {
                // 如果已存在，更新时间
                Db::name('user_actions')
                    ->where('id', $existing['id'])
                    ->update(['updated_at' => date('Y-m-d H:i:s')]);
                
                $message = $action_type == 'like' ? '已在收藏列表中' : '已在下载记录中';
                return $this->jsonResponse(['action_id' => $existing['id']], 200, $message);
            } else {
                // 插入新记录
                $data = [
                    'user_id' => $user_id,
                    'image_id' => $image_id,
                    'action_type' => $action_type,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                
                $action_id = Db::name('user_actions')->insertGetId($data);
                
                if ($action_id) {
                    $message = $action_type == 'like' ? '收藏成功' : '下载记录已保存';
                    return $this->jsonResponse(['action_id' => $action_id], 200, $message);
                } else {
                    return $this->jsonResponse([], 500, '操作失败，请稍后重试');
                }
            }
            
        } catch (\Exception $e) {
            // 记录错误日志
            throw $e;
            // return $this->jsonResponse([], 500, '系统错误，请稍后重试');
        }
    }
    
    /**
     * 移除用户操作记录（取消喜欢/删除下载记录）
     * @param Request $request
     * @return \think\response\Json
     */
    public function removeAction($image_id,$action_type)
    {
        try {
            // 获取请求参数
            $image_id = intval($image_id);
            $action_type = trim($action_type);
            
            // 参数验证
            if (empty($image_id)) {
                return $this->jsonResponse([], 400, '桌布ID不能为空');
            }
            
            if (!in_array($action_type, ['like', 'download'])) {
                return $this->jsonResponse([], 400, '操作类型无效');
            }
            
            // 获取用户ID
            $user_id = $this->_user_id;
            if (empty($user_id)) {
                return $this->jsonResponse([], 401, '请先登录');
            }
            $action_field = $action_type == 'like' ? 'like_cnt' : 'download_cnt';
            Db::name('wallpaper')->where('id', $image_id)->setDec($action_field);
            
            // 删除记录
            $result = Db::name('user_actions')
                ->where([
                    'user_id' => $user_id,
                    'image_id' => $image_id,
                    'action_type' => $action_type
                ])
                ->delete();
            
            if ($result) {
                $message = $action_type == 'like' ? '已取消收藏' : '已删除下载记录';
                return $this->jsonResponse([], 200, $message);
            } else {
                return $this->jsonResponse([], 404, '记录不存在');
            }
            
        } catch (\Exception $e) {
            // 记录错误日志
            throw $e;
            // return $this->jsonResponse([], 500, '系统错误，请稍后重试');
        }
    }
    
   
    
    /**
     * 根据操作类型和桌布类型获取用户操作记录
     */
    private function getUserActionsByType($actionType, $wallpaperTypes = [], $limit = null)
    {
        $query = Db::name('user_actions')
            ->alias('ua')
            ->join('wallpaper wi', 'ua.image_id = wi.id')
            ->where([
                'ua.user_id' => $this->_user_id,
                'ua.action_type' => $actionType
            ])
            ->field('wi.*, ua.created_at as action_time, ua.updated_at')
            ->order('ua.updated_at desc');
        
        if (!empty($wallpaperTypes)) {
            $query->where('wi.type', 'in', $wallpaperTypes);
        }
        
        if ($limit) {
            $query->limit($limit);
        }
        
        $actions = $query->select();
        // debug_dump($actions,$query->getLastSql());
        
        // 根据桌布类型确定格式化类型
        $formatType = '';
        if (!empty($wallpaperTypes)) {
            if (in_array('mobile', $wallpaperTypes) || in_array('dynamic_mobile', $wallpaperTypes)) {
                $formatType = 'mobile';
            } elseif (in_array('desktop', $wallpaperTypes) || in_array('dynamic_desktop', $wallpaperTypes)) {
                $formatType = 'desktop';
            }
        }
        
        return $this->_formatWallpaper($actions);
    }
    
    
    /**
     * 电脑桌布收藏页面
     */
    public function desktopFavorites()
    {
        // 檢查用戶登錄狀態
        if (empty($this->_user_id)) {
            $this->redirect('/');
        }
        
        // 獲取收藏的電腦桌布
        $wallpapers = $this->getUserActionsByType('like', ['desktop', 'dynamic_desktop']);
        
        $this->assign([
            'wallpapers' => $wallpapers,
            'count' => count($wallpapers),
            'page_title' => '我收藏的電腦桌布',
            'page_description' => '查看我收藏的電腦桌布。',
        ]);
        
        return $this->fetch();
    }
    
    /**
     * 手机桌布收藏页面
     */
    public function mobileFavorites()
    {
        // 檢查用戶登錄狀態
        if (empty($this->_user_id)) {
            $this->redirect('/');
        }
        
        // 獲取收藏的手機桌布
        $wallpapers = $this->getUserActionsByType('like', ['mobile', 'dynamic_mobile']);
        
        $this->assign([
            'wallpapers' => $wallpapers,
            'count' => count($wallpapers),
            'page_title' => '我收藏的手機桌布',
            'page_description' => '查看我收藏的手機桌布。',
        ]);
        
        return $this->fetch();
    }
    
    /**
     * 电脑桌布下载页面
     */
    public function desktopDownloads()
    {
        // 檢查用戶登錄狀態
        if (empty($this->_user_id)) {
            $this->redirect('/');
        }
        
        // 獲取下載的電腦桌布
        $wallpapers = $this->getUserActionsByType('download', ['desktop', 'dynamic_desktop']);
        
        $this->assign([
            'wallpapers' => $wallpapers,
            'count' => count($wallpapers),
            'page_title' => '我下載的電腦桌布',
            'page_description' => '查看我下載的電腦桌布。',
        ]);
        
        return $this->fetch();
    }
    
    /**
     * 手机桌布下载页面
     */
    public function mobileDownloads()
    {
        // 檢查用戶登錄狀態
        if (empty($this->_user_id)) {
            $this->redirect('/');
        }
        
        // 獲取下載的手機桌布
        $wallpapers = $this->getUserActionsByType('download', ['mobile', 'dynamic_mobile']);
        
        $this->assign([
            'wallpapers' => $wallpapers,
            'count' => count($wallpapers),
            'page_title' => '我下載的手機桌布',
            'page_description' => '查看我下載的手機桌布。',
        ]);
        
        return $this->fetch();
    }

    public function generateDesktop()
    {
        // 获取当前用户ID
        $user_id = $this->_user_id;
        if (empty($user_id)) {
            $this->redirect('/');
        }
        
        $wallpapers = Db('wallpaper_generate')->where(['user_id'=>$user_id,'wall_type'=>'desktop'])->order('id desc')->select();
        $this->assign([
            'wallpapers' => $wallpapers,
            'count' => count($wallpapers),
            'page_title' => '我產生的電腦桌布',
            'page_description' => '查看我產生的電腦桌布。',
        ]);
        
        return $this->fetch();
    }

    public function generateMobile()
    {
        // 获取当前用户ID
        $user_id = $this->_user_id;
        if (empty($user_id)) {
            $this->redirect('/');
        }
        
        $wallpapers = Db('wallpaper_generate')->where(['user_id'=>$user_id,'wall_type'=>'mobile'])->order('id desc')->select();
        $this->assign([
            'wallpapers' => $wallpapers,
            'count' => count($wallpapers),
            'page_title' => '我產生的手機桌布',
            'page_description' => '查看我產生的手機桌布。',
        ]);
        
        return $this->fetch();
    }
}
